from flask import request
from flask import session, jsonify

from info import constants
from info.models import User, News, Category
from utils.response_code import RET
from . import index_blue
from info import redis_store
from flask import render_template,current_app


# 获取新闻列表newslist
# 请求路径：newslist
#请求方式：get
# 请求参数：cur_click,page,perpage
# 返回值：json数据
@index_blue.route('/newslist')
def news_list():
    # 获取请求参数,如果没有就给定默认值
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    # 参数类型转换,为分页查询做准备
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        cid = 1
        page = 1
        per_page = 10

    # 分页查询
    try:
        # 判断分类是否不等于１,提取出查询条件
        query_condition = ''
        if cid != 1:
            query_condition = News.category_id == cid

        paginage = News.query.filter(query_condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻列表失败')

    # 总页数，当前也，当前也对象
    totalPage = paginage.pages
    currentPage = paginage.page
    items = paginage.items

    # 获取当前也对象并转化成字典
    newsList = []
    for item in items:
        newsList.append(item.to_dict())

    # data = {
    #     'totalPage':totalPage,
    #     'currentPage':currentPage,
    #     'newsList':newsList
    # }

    return jsonify(errno=RET.OK,errmsg='获取新闻列表成功',totalPage=totalPage,currentPage=currentPage,newsList=newsList)


@index_blue.route("/")
def hello_world():

    # 获取用户登陆状态
    user_id = session.get('user_id')
    user = None
    # 如果客户存在取出客户信息
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 点击排行数据显示,获取新闻排行
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取排行新闻失败')
    # 将新闻转化成新闻列表对象
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())

    # 获取新闻分类
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻列表失败')

    # 将新闻列表转化成字典
    category_list = []
    for category in categorys:
        category_list.append(category.to_dict())


    data = {
        'user_info':user.to_dict() if user else '',
        'click_news_list':click_news_list,
        'category_list':category_list
    }

    return render_template('news/index.html',data=data)



@index_blue.route('/favicon.ico')
def web_logo():

    return current_app.send_static_file('news/favicon.ico')